from kivy.uix.widget import Widget
from kivy.core.window import Window

class KeyListener(Widget):
    """KeyListener
    
       You must declare a function whose args contains (keycode,modifiers),
       a simple example like this:
       
       def processor(keycode,modifiers):
           pass
       
       usage: xx = KeyListener(processor = processor)
       warning: the keycode is a cupple which contains numeric arg and text like this
       
       (97,'a')
       
    """
    
    def __init__(self,**kwargs):
        super(KeyListener,self).__init__(**kwargs)
        self._keyboard=Window.request_keyboard(self._keyboard_close,self)
        self._keyboard.bind(on_key_down=self._keyboard_down)
        self.processor=kwargs['processor']
        
    def _keyboard_close(self):
        self._keyboard.unbind(on_key_down=self._keyboard_down)
        
    def _keyboard_down(self,keyboard,keycode,text,modifiers):
        self.processor(keycode,modifiers)
        return True